import http from '@ohos.net.http';
import { NewInfo } from '../model/news/NewsModel';
import httpUtils from '../utils/HttpUtils';
import config from './Config';
import router from '@ohos.router';
import preferencesUtil from '../utils/PreferencesUtil';
import { PreferencesEnum } from '../utils/enmu/PreferencesEnmu';
import { UserInfo } from '../model/user/UserInfo';
import preferences from '@ohos.data.preferences';
/**
 * 获取新闻热搜数据
 */

class LoginAPI {


  // 获取验证码
  getCaptcha(userId: string, question: string, modelUsed: string): Promise<NewInfo> {
    return new Promise<NewInfo>((resolve, reject) => {
      let httpRequest = http.createHttp()

      httpRequest.request(
        `${config.baseURL}/captchaImage`,
        {
          method: http.RequestMethod.GET,
          header: {
            "Content-Type": "application/json"
          }
        }
      ).then(res => {
        if (res.responseCode == 200) {
          //console.log(JSON.parse(res.result.toString()).data.title + "dao");
          resolve(JSON.parse(res.result.toString()).data)
        } else {
          console.log("请求失败")
          reject("请求失败")
        }
      })
    })
  }
  // 登录接口
  async login(userName: string, password: string): Promise<any> {
    let res = await httpUtils.post(`/login`, {
      "username": userName,
      "password": password
    })

    console.log(res.code)

    if (res.code == 200) {
      // 将token存入preference
      await preferencesUtil.loadPreferences(this, PreferencesEnum.USER_PREFERENCES);
      preferencesUtil.putPreferences(PreferencesEnum.USER_PREFERENCES, PreferencesEnum.TOKEN, config.tokenPrefix + res.token)
      preferencesUtil.putPreferences(PreferencesEnum.USER_PREFERENCES, PreferencesEnum.USER_NAME, userName)

      //存入用户ID
      preferencesUtil.putPreferences(PreferencesEnum.USER_PREFERENCES, "USER_ID", res.userId)
    }
    return res;

  }
  // 注册
  async register(userName: string, password: string): Promise<any> {
    let res = await httpUtils.post(`/register`, {
      "password": userName,
      "username": password
    })
    return res
  }

  async getUserInfo(): Promise<UserInfo> {
    try {
      let res = await httpUtils.get(`/getInfo`)
      if (res.code == 200) {
        // console.log(JSON.parse(res.result.toString()).rows[0].title + "获取新闻列表成功");
        // 将用户信息存入preference
        await preferencesUtil.putPreferences(PreferencesEnum.USER_PREFERENCES, PreferencesEnum.USER_INFO, res.user)
        await preferencesUtil.putPreferences(PreferencesEnum.USER_PREFERENCES, PreferencesEnum.USER_NAME, res.user.userName)
        return res.user
      } else {
        console.log(`请求失败:[getInfo]` + res.msg)
      }
    } catch (err) {
      console.log(`请求失败:[getInfo]` + err)
    }
  }
}

let loginAPI = new LoginAPI()

export default loginAPI
